package com.situ.mall.common.service.impl;

import com.situ.mall.common.entity.*;
import com.situ.mall.common.mapper.*;
import com.situ.mall.common.service.IOrderInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.situ.mall.common.service.IpayService;
import com.situ.mall.common.util.RequestUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.time.LocalDateTime;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author membergpf
 * @since 2023-03-18
 */
@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements IOrderInfoService {
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private ProductMapper productMapper;
    @Resource
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private OrderAddressMapper orderAddressMapper;
    @Autowired
    private MemberAddressMapper memberAddressMapper;
    @Autowired
    private IpayService payService;
    @Override
    @Transactional
    public String saveOrder(String ids, Integer addId) {
        //获取当前登录用户
        Member m = RequestUtil.getCurrent();
        BigDecimal sumPrice = new BigDecimal(0);
        for (String cartId : ids.split(",")){
            Cart cart = cartMapper.selectById(Integer.parseInt(cartId));
            Product p = productMapper.selectById(cart.getProductId());
            sumPrice = sumPrice.add(p.getPrice().multiply(BigDecimal.valueOf(cart.getAmount())));
        }

        //保存orderinfo数据
        OrderInfo order = new OrderInfo();
        order.setCreatetime(LocalDateTime.now());
        order.setMemberId(m.getId());
        order.setStatus("待支付");
        //订单号不能重复
        //自定义流水号
        //查数据库最大code是几
        String pre = "TEST2304";
        order.setCode(getNextNo(pre));
        order.setPrice(sumPrice);
        //保存订单主表的数据
        baseMapper.insert(order);


        //订单详情表
        for(String cartId : ids.split(",")){
            OrderDetail orderDetail = new OrderDetail();
            Cart cart = cartMapper.selectById(Integer.parseInt(cartId));
            //Product p = productMapper.selectById(cart.getProductId());
            orderDetail.setAmount(cart.getAmount());
            orderDetail.setProductId(cart.getProductId());
            orderDetail.setOrderId(order.getId());
            orderDetail.setSinglePrice(order.getPrice().divide(BigDecimal.valueOf(cart.getAmount())));
            orderDetailMapper.insert(orderDetail);
            cartMapper.deleteById(Integer.parseInt(cartId));//删除购物车数据
        }
        //用户地址档案
        MemberAddress ma = memberAddressMapper.selectById(addId);

        //订单地址表
        OrderAddress orderAddress = new OrderAddress();
        orderAddress.setOrderId(order.getId());
        BeanUtils.copyProperties(ma ,orderAddress);//属性拷贝
        orderAddress.setId(null);
        orderAddressMapper.insert(orderAddress);

        //调用支付的service对接支付
        return payService.createPayOrder(order);

    }

    //获取一个前缀，返回下一个订单号
    private synchronized String getNextNo(String pre){
        //获取此前缀最大值
        Object obj = redisTemplate.opsForValue().get(pre);
        int nextNo;
        if(obj == null){
            String maxCode = baseMapper.selectMaxCode(pre);
            if (maxCode == null) {
                nextNo = 1;
            }else {
                String no = maxCode.substring(pre.length());
                nextNo = Integer.parseInt(no) + 1;
            }
            redisTemplate.opsForValue().set(pre, nextNo + 1);
        }else {
            nextNo = (int)obj;
            redisTemplate.opsForValue().set(pre, nextNo + 1);
        }

        return pre+new DecimalFormat("0000").format(nextNo);
    }

}
